﻿using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace FrameWork.DataHelper
{
    public static class Valid
    {
        /**
         * 校验Id有效性
         */
        public static async Task<T> ValidId<T>(DbSet<T> table, string Id) where T : class
        {
            //判空
            if (string.IsNullOrEmpty(Id))
            {
                return null;
            };

            //校验Id有效性
            var query = await table.FindAsync(Id);
            return query;
        }

        /**
         * 校验Id有效性列表
         */
        public static async Task<List<T>> ValidIdList<T>(DbSet<T> table, List<string> Ids) where T : class
        {
            //判空
            if (Ids == null || Ids.Count == 0)
            {
                return null;
            }

            var idProperty = typeof(T).GetProperty("Id");
            if (idProperty == null)
            {
                return null;
            }
            // 使用表达式树构建查询
            var parameter = Expression.Parameter(typeof(T), "a");
            var property = Expression.Property(parameter, idProperty);
            var toString = Expression.Call(property, "ToString", null, null);
            var contains = Expression.Call(typeof(Enumerable), "Contains", new[] { typeof(string) },
                Expression.Constant(Ids), toString);
            var lambda = Expression.Lambda<Func<T, bool>>(contains, parameter);

            // 执行查询
            var query = await table
                .Where(lambda)
                .ToListAsync();
            //查找id
            //var query = await table
            //    .Where(a => Ids.Contains(idProperty.GetValue(a).ToString()))
            //    .ToListAsync();

            if (query.Count == 0)
            {
                return null;
            }

            return query;
        }
    }
}
